package com.liaoyin.travel.service.attendance;

import com.google.common.collect.Lists;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.entity.UserTeam;
import com.liaoyin.travel.entity.Users;
import com.liaoyin.travel.entity.attendance.AttendanceManagement;
import com.liaoyin.travel.entity.attendance.AttendanceRecord;
import com.liaoyin.travel.entity.team.Team;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.service.team.TeamService;
import com.liaoyin.travel.util.DateUtil;
import com.liaoyin.travel.util.LocationUtils;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.StringUtil;
import com.liaoyin.travel.view.mine.attendance.AbnormalUserView;
import com.liaoyin.travel.view.mine.attendance.AttendanceDistanceInfoView;
import com.liaoyin.travel.view.mine.attendance.AttendanceMonitoringView;
import com.liaoyin.travel.view.moble.attendance.AttendanceSetView;
import com.liaoyin.travel.view.moble.attendance.AttendanceWeekDayView;
import com.liaoyin.travel.view.moble.attendance.ClockSettingsView;
import com.liaoyin.travel.view.moble.attendance.StaffTaiyakiAttendanceInfoView;
import com.liaoyin.travel.view.user.ClassificationInfo;
import com.liaoyin.travel.vo.attendance.AttendanceManageVo;
import com.liaoyin.travel.vo.attendance.MobileAttencanceRateVO;
import com.liaoyin.travel.vo.attendance.MobileAttendanceRecordVO;
import com.liaoyin.travel.vo.attendance.MobileAttendanceStatVO;
import com.liaoyin.travel.vo.request.MobileAttendanceStatRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * 考勤新需求
 *
 * @author kuang.jiazhuo
 * @date 2019-11-19 19:30
 */
@Service
public class AttendanceNewService {

    @Resource
    private AttendanceUserService attendanceUserService;

    @Resource
    private AttendanceRecordService attendanceRecordService;

    @Resource
    private ManagementService managementService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private TeamService teamService;

    /**
     * @方法名：judgeCheckInIsAllowed
     * @描述： 移动端员工传入经纬度判断是否到考勤打卡的附近
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/19 19:35
     */
    public boolean judgeCheckInIsAllowed(String lat, String log,UserInfo user) {
        //判断是否登录顺便拿到登录信息
        if(user==null) {
            UserInfo userInfo = PartyUtil.getCurrentUserInfo();
            if(userInfo == null) {
                throw new BusinessException("user.isNotLogin");
            }
            user = userInfo;
        }
        /** 景区id */
        String scenicId = user.getScenicId();
        AttendanceDistanceInfoView attendanceDistanceInfoView = this.attendanceUserService.selectAttendanceDistanceInfoViewByUserId(user.getId(),scenicId);
        if(attendanceDistanceInfoView==null) {
            throw new BusinessException("at.is.null");
        }
        double disparity = LocationUtils.getDistance(Double.valueOf(lat), Double.valueOf(log), Double.valueOf(attendanceDistanceInfoView.getLat()), Double.valueOf(attendanceDistanceInfoView.getLog()));
        if(Math.abs(disparity) > attendanceDistanceInfoView.getAttendanceRange()) {
            return false;
        }
        return true;
    }



    /**
     * 描述:判断是否在考勤范围之内
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/19 19:35
     * @param afferentLog 传入的经度
     * @param afferentLat 传入的纬度
     * @param settingLog 设置的经度
     * @param settingLat 设置的纬度
     * @param attendanceRange 允许考勤的偏离距离
     * @return 是否在考勤范围之内
     */
    public boolean determineIfItIsInTheAttendanceRange(String afferentLog, String afferentLat,String settingLog,String settingLat,double attendanceRange){
        double disparity = LocationUtils.getDistance(Double.valueOf(afferentLat), Double.valueOf(afferentLog), Double.valueOf(settingLat), Double.valueOf(settingLog));
        if(Math.abs(disparity) > attendanceRange) {
            return false;
        }
        return true;
    }

    /**
     * @方法名：getTheDayIsClock
     * @描述： 获取员工当天的考勤情况
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/21 23:44
     */
    public StaffTaiyakiAttendanceInfoView getTheDayIsClock(String date) {

        System.err.println("date="+date);
        UserInfo userInfo = PartyUtil.getCurrentUserInfo();
        if(userInfo == null) {
            throw new BusinessException("user.isNotLogin");
        }

        StaffTaiyakiAttendanceInfoView staffTaiyakiAttendanceInfoView = new StaffTaiyakiAttendanceInfoView();
        ClockSettingsView clockSettingsView = this.managementService.selectClockSettingsViewByUserID(userInfo.getId());
        System.err.println("clockSettingsView="+clockSettingsView);
        if(clockSettingsView==null){
            throw new BusinessException("attendance.group.not.included");
        }
        AttendanceRecord attendanceRecord = this.attendanceRecordService.selectAttendanceRecordByUserIdAndDateOfAttendance(userInfo.getId(), LocalDate.parse(date));
        System.err.println("attendanceRecord="+attendanceRecord);
        if(attendanceRecord==null){
            staffTaiyakiAttendanceInfoView.setClockFrequency(0);
        }else{
            staffTaiyakiAttendanceInfoView.setAttendanceRecord(attendanceRecord);
            staffTaiyakiAttendanceInfoView.setClockFrequency(attendanceRecord.getClockFrequency());
        }

        System.err.println(staffTaiyakiAttendanceInfoView);
        return staffTaiyakiAttendanceInfoView;
    }

    /**
     * @方法名：selectAttendanceDateTime
     * @描述： 查询员工的考勤工作日和打卡时间
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 23:24
     */
    public AttendanceSetView selectAttendanceDateTime(String userId) {
        if(userId==null){
            UserInfo userInfo = PartyUtil.getCurrentUserInfo();
            if(userInfo == null) {
                throw new BusinessException("user.isNotLogin");
            }
            userId = userInfo.getId();
        }

        AttendanceManagement attendanceManagement = this.managementService.selectAttendanceManagementByUserId(userId);
        if(attendanceManagement==null){
            throw new BusinessException("not.attendance.set");
        }
        List<AttendanceWeekDayView> attendanceWeekDayViews = this.attendanceUserService.selectAttendanceDay(userId);
        AttendanceSetView attendanceSetView = new AttendanceSetView();
        attendanceSetView.setClockInTime(attendanceManagement.getAttendanceStartTime())
                .setClockOutTime(attendanceManagement.getAttendanceEndTime())
                .setWeekDays(attendanceWeekDayViews);
        return attendanceSetView;
    }

    /**
     * @author 王海洋
     * @methodName: isEnableAttendance
     * @methodDesc: 当天是否可以打卡
     * @description:
     * @param: []
     * @return boolean
     * @create 2019-11-25 19:14
     **/
    public boolean isEnableAttendance(){
        String userId = null;
        if(userId==null){
            UserInfo user = PartyUtil.getCurrentUserInfo();
            if(user == null) {
                throw new BusinessException("user.isNotLogin");
            }
            userId = user.getId();
        }
        AttendanceManageVo attendanceManageVo = managementService.selectAttendanceManageVoByUserId(userId);
        if(attendanceManageVo==null){
            return false;
        }
        String weekDayNum = DateUtil.getWeekOfDateNum(new Date());
        if(!attendanceManageVo.getAttendanceDays().contains(weekDayNum)){
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        boolean hasOutOrLeave = this.attendanceRecordService.hasLeaveOrOut(time,userId);
        if(hasOutOrLeave){
            return false;
        }
        return true;
    }

    /**
     * @author 王海洋
     * @methodName: getMobileAttendanceStat
     * @methodDesc: 打卡统计
     * @description:
     * @param: [startDate, endDate]
     * @return com.liaoyin.travel.vo.attendance.MobileAttendanceStatVO
     * @create 2019-11-26 10:45
     **/
    public MobileAttencanceRateVO getMobileAttendanceStat(MobileAttendanceStatRequestVO mobileAttendanceStatRequestVO){
        UserInfo activeUser = PartyUtil.getCurrentUserInfo();
        Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));
        //景区id
        String scenicId = activeUser.getScenicId();
        mobileAttendanceStatRequestVO.setScenicId(scenicId);

        StringBuffer teamId = new StringBuffer();
        int userCnt = 0;
        //传入的用户id
        String userId = mobileAttendanceStatRequestVO.getUserId();
        if(userId != null && !"".equals(userId)) {
            //判断是否有权限查询(是不是部门经理)
//            if(activeUser.getAssumeOffice()!=null && activeUser.getAssumeOffice().intValue()==1) {
//                List<UserTeam> usertramList = activeUser.getUserTeamList();
//                if(usertramList==null || usertramList.size() == 0) {
//                    throw new BusinessException("team.is.null");
//                }
//                for(UserTeam u:usertramList) {
//                    teamId.append(u.getTeamId()+",");
//                }
//                boolean b = this.usersService.judgeThisUserInTeam(teamId.toString(), mobileAttendanceStatRequestVO.getUserId());
//                if(!b) {
//                    throw new BusinessException("auth.is.erreo");
//                }
//                mobileAttendanceStatRequestVO.setTeamIds(teamId.toString());
//            }
            userCnt = mobileAttendanceStatRequestVO.getUserId().split(",").length;
        } else if(mobileAttendanceStatRequestVO.getUserId().equals("1")){
            if(!activeUser.getUserType().equals("2")){
                mobileAttendanceStatRequestVO.setUserId(activeUser.getId());
            }
            List<Team> teamList= teamService.selectAllTeam();
            for(Team team:teamList) {
                teamId.append(team.getId()+",");
            }
            mobileAttendanceStatRequestVO.setTeamIds(teamId.toString());
            userCnt = this.usersService.selectUsersCnt(teamId.toString());
        }else {
            if(!activeUser.getUserType().equals("2")){
                mobileAttendanceStatRequestVO.setUserId(activeUser.getId());
            }
            List<UserTeam> teamList= activeUser.getUserTeamList();
            for(UserTeam team:teamList) {
                teamId.append(team.getTeamId()+",");
            }
            mobileAttendanceStatRequestVO.setTeamIds(teamId.toString());
            userCnt = this.usersService.selectUsersCnt(teamId.toString());
        }
        if(StringUtil.isNotEmpty(mobileAttendanceStatRequestVO.getEndDate()) && mobileAttendanceStatRequestVO.getEndDate().compareTo(LocalDate.now().toString())>=1){
            mobileAttendanceStatRequestVO.setEndDate(LocalDate.now().toString());
        }
        MobileAttencanceRateVO mobileAttencanceRateVO = new MobileAttencanceRateVO();
        MobileAttendanceStatVO mobileAttendanceStatVO = this.attendanceRecordService.getMobileAttendanceStat(mobileAttendanceStatRequestVO);

        List<String> normalUserIds = this.attendanceRecordService.getNormalAttendanceCnt(mobileAttendanceStatRequestVO);
        int normalCnt = normalUserIds.size();
        //int abnormalCnt = this.attendanceRecordService.getAbnormalAttendanceCnt(mobileAttendanceStatRequestVO);


        /**
         * 获取缺卡记录
         */
        List<Map<String,String>> lists = this.attendanceRecordService.getLackRecord(mobileAttendanceStatRequestVO);
        if(lists!=null && lists.size()>0){
            mobileAttendanceStatVO.setMissCnt(String.valueOf(lists.size()));
        }else{
            mobileAttendanceStatVO.setMissCnt("0");
        }

        if(mobileAttencanceRateVO!=null){
            mobileAttencanceRateVO.setMobileAttendanceStatVO(mobileAttendanceStatVO);
        }
        List<MobileAttendanceRecordVO> recordVOList = this.attendanceRecordService.getRecordList(mobileAttendanceStatRequestVO);

        if(recordVOList!=null && recordVOList.size()>0){
            for(MobileAttendanceRecordVO mobileAttendanceRecordVO:recordVOList){
                String weekDay = mobileAttendanceRecordVO.getWeekDay();
                if(StringUtil.isEmpty(mobileAttendanceRecordVO.getAttendanceStatus()) && mobileAttendanceRecordVO.getAttendanceDate().equals(LocalDate.now().toString())){
                    List<String> normalStates = Lists.newArrayList("1","6","9","11","12");
                    if(StringUtil.isNotEmpty(mobileAttendanceRecordVO.getInState()) && !normalUserIds.contains(mobileAttendanceRecordVO.getUserId()) &&
                            normalStates.contains(mobileAttendanceRecordVO.getInState())){
                        normalCnt++;
                    }
                }
                switch (weekDay){
                    case "7":
                        weekDay="天";
                        break;
                    case "1":
                        weekDay="一";
                        break;
                    case "2":
                        weekDay="二";
                        break;
                    case "3":
                        weekDay="三";
                        break;
                    case "4":
                        weekDay="四";
                        break;
                    case "5":
                        weekDay="五";
                        break;
                    case "6":
                        weekDay="六";
                        break;
                }
                mobileAttendanceRecordVO.setWeekDay(weekDay);
            }
            mobileAttencanceRateVO.setAttendanceRecordVOList(recordVOList);
        }
        int days = DateUtil.calculateLocalDateDaysDifference(LocalDate.parse(mobileAttendanceStatRequestVO.getStartDate()),LocalDate.parse(mobileAttendanceStatRequestVO.getEndDate()))+1;
        mobileAttencanceRateVO.setNormalCnt(normalCnt);
        mobileAttencanceRateVO.setUnormalCnt(userCnt*days-normalCnt);
        return mobileAttencanceRateVO;
    }

    /**
     * @方法名：getMobileAttendanceStat
     * @描述： 打卡统计
     * @作者： kjz
     * @日期： Created in 2020/4/23 16:59
     */
   /* public MobileAttencanceRateVO getMobileAttendanceStat(MobileAttendanceStatRequestVO mobileAttendanceStatRequestVO){
        System.err.println(JSON.toJSONString(mobileAttendanceStatRequestVO));
        //获取当前登录用户信息
        UserInfo activeUser = PartyUtil.getCurrentUserInfo();
        Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));
        *//** 景区id*//*
        String scenicId = activeUser.getScenicId();
        mobileAttendanceStatRequestVO.setScenicId(scenicId);

        //传入的用户id
        String userId = mobileAttendanceStatRequestVO.getUserId();

        *//**
         * 如果用户id为空，就是管理端打开数据统计的考勤管理没有传查询条件，默认查当前管理端用户部门的考勤信息
         *//*
        if(userId != null && !"".equals(userId)) {
           //确认是管理端登陆
            if(activeUser.getUserType().equals("2")){
                String teamId = activeUser.getUserTeamList().get(0).getTeamId();
                mobileAttendanceStatRequestVO.setTeamIds(teamId);
            }
        }
        MobileAttendanceStatVO mobileAttendanceStatVO = this.attendanceRecordService.getMobileAttendanceStat(mobileAttendanceStatRequestVO);

        StringBuffer teamId = new StringBuffer();
        //用户id数量
        int userCnt = 0;
        //传入的用户id
        String userId = mobileAttendanceStatRequestVO.getUserId();
        if(userId != null && !"".equals(userId)) {
            userCnt = mobileAttendanceStatRequestVO.getUserId().split(",").length;

        } else if(mobileAttendanceStatRequestVO.getUserId().equals("1")){
            if(!activeUser.getUserType().equals("2")){
                mobileAttendanceStatRequestVO.setUserId(activeUser.getId());
            }
            //查询所有的部门
            List<Team> teamList= teamService.selectAllTeam();
            for(Team team:teamList) {
                teamId.append(team.getId()+",");
            }
            mobileAttendanceStatRequestVO.setTeamIds(teamId.toString());
            userCnt = this.usersService.selectUsersCnt(teamId.toString());
        }else {
            if(!activeUser.getUserType().equals("2")){
                mobileAttendanceStatRequestVO.setUserId(activeUser.getId());
            }
            List<UserTeam> teamList= activeUser.getUserTeamList();
            for(UserTeam team:teamList) {
                teamId.append(team.getTeamId()+",");
            }
            mobileAttendanceStatRequestVO.setTeamIds(teamId.toString());
            userCnt = this.usersService.selectUsersCnt(teamId.toString());
        }
        if(StringUtil.isNotEmpty(mobileAttendanceStatRequestVO.getEndDate()) && mobileAttendanceStatRequestVO.getEndDate().compareTo(LocalDate.now().toString())>=1){
            mobileAttendanceStatRequestVO.setEndDate(LocalDate.now().toString());
        }
        MobileAttencanceRateVO mobileAttencanceRateVO = new MobileAttencanceRateVO();


        List<String> normalUserIds = this.attendanceRecordService.getNormalAttendanceCnt(mobileAttendanceStatRequestVO);
        int normalCnt = normalUserIds.size();
        //int abnormalCnt = this.attendanceRecordService.getAbnormalAttendanceCnt(mobileAttendanceStatRequestVO);


        *//**
         * 获取缺卡记录
         *//*
        List<Map<String,String>> lists = this.attendanceRecordService.getLackRecord(mobileAttendanceStatRequestVO);
        if(lists!=null && lists.size()>0){
            mobileAttendanceStatVO.setMissCnt(String.valueOf(lists.size()));
        }else{
            mobileAttendanceStatVO.setMissCnt("0");
        }

        if(mobileAttencanceRateVO!=null){
            mobileAttencanceRateVO.setMobileAttendanceStatVO(mobileAttendanceStatVO);
        }
        List<MobileAttendanceRecordVO> recordVOList = this.attendanceRecordService.getRecordList(mobileAttendanceStatRequestVO);

        if(recordVOList!=null && recordVOList.size()>0){
            for(MobileAttendanceRecordVO mobileAttendanceRecordVO:recordVOList){
                String weekDay = mobileAttendanceRecordVO.getWeekDay();
                *//*if(StringUtil.isEmpty(mobileAttendanceRecordVO.getAttendanceStatus()) && mobileAttendanceRecordVO.getAttendanceDate().equals(LocalDate.now().toString())){
                    List<String> normalStates = Lists.newArrayList("1","6","9","11","12");
                    if(StringUtil.isNotEmpty(mobileAttendanceRecordVO.getInState()) && !normalUserIds.contains(mobileAttendanceRecordVO.getUserId()) &&
                            normalStates.contains(mobileAttendanceRecordVO.getInState())){
                        normalCnt++;
                    }
                }*//*
                switch (weekDay){
                    case "7":
                        weekDay="天";
                        break;
                    case "1":
                        weekDay="一";
                        break;
                    case "2":
                        weekDay="二";
                        break;
                    case "3":
                        weekDay="三";
                        break;
                    case "4":
                        weekDay="四";
                        break;
                    case "5":
                        weekDay="五";
                        break;
                    case "6":
                        weekDay="六";
                        break;
                }
                mobileAttendanceRecordVO.setWeekDay(weekDay);
            }
            mobileAttencanceRateVO.setAttendanceRecordVOList(recordVOList);
        }
        int days = DateUtil.calculateLocalDateDaysDifference(LocalDate.parse(mobileAttendanceStatRequestVO.getStartDate()),LocalDate.parse(mobileAttendanceStatRequestVO.getEndDate()))+1;
        mobileAttencanceRateVO.setNormalCnt(normalCnt);
        mobileAttencanceRateVO.setUnormalCnt(userCnt*days-normalCnt);
        return mobileAttencanceRateVO;
    }*/

    public List<Map<String,String>> getAttendanceRecordByType(MobileAttendanceStatRequestVO mobileAttendanceStatRequestVO){
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null ) {
            throw new BusinessException("not.login");
        }
        /** 景区id*/
        String scenicId = user.getScenicId();
        mobileAttendanceStatRequestVO.setScenicId(scenicId);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtil.isEmpty(mobileAttendanceStatRequestVO.getEndDate())){
            mobileAttendanceStatRequestVO.setEndDate(sdf.format(new Date()));
        }
        if(StringUtil.isNotEmpty(mobileAttendanceStatRequestVO.getEndDate()) && mobileAttendanceStatRequestVO.getEndDate().compareTo(LocalDate.now().toString())>=1){
            mobileAttendanceStatRequestVO.setEndDate(LocalDate.now().toString());
        }
        List<Map<String,String>> list = Lists.newArrayList();
        if(mobileAttendanceStatRequestVO.getUserId() != null && !"".equals(mobileAttendanceStatRequestVO.getUserId())) {

        }else {
            mobileAttendanceStatRequestVO.setUserId(user.getId());
        }
        if(mobileAttendanceStatRequestVO.getAttendanceStatus().equals("2")){
            list =  this.attendanceRecordService.getLackRecord(mobileAttendanceStatRequestVO);
        }else{
            list = this.attendanceRecordService.getAttendanceRecordByType(mobileAttendanceStatRequestVO);
        }
        for(Map<String,String> map:list){
            String weekDay = String.valueOf(map.get("weekDay"));
            switch (weekDay){
                case "0":
                    weekDay="天";
                    break;
                case "7":
                    weekDay="天";
                    break;
                case "1":
                    weekDay="一";
                    break;
                case "2":
                    weekDay="二";
                    break;
                case "3":
                    weekDay="三";
                    break;
                case "4":
                    weekDay="四";
                    break;
                case "5":
                    weekDay="五";
                    break;
                case "6":
                    weekDay="六";
                    break;
            }
            map.put("weekDay",weekDay);
        }
        return list;
    }

    /**
     * @方法名：selectAttendanceMonitoringByDate
     * @描述： 移动端根据日期查询考勤监控数据
     * @作者： kjz
     * @日期： Created in 2020/4/20 16:21
     */
    public AttendanceMonitoringView selectAttendanceMonitoringByDate(String date) {
        if(date==null || "".equals(date)){
            throw new BusinessException("date.is.null");
        }

        //获取当前用户登录信息
        UserInfo activeUser = PartyUtil.getCurrentUserInfo();
        Optional.ofNullable(activeUser).orElseThrow(() -> new BusinessException("not.login"));

        //把时间换成前一天的时间，逻辑已经作废
//        String resultDate = DateUtil.getYesterdayStrByDateStr(date);
        String resultDate = date;
        System.out.println("resultDate="+resultDate);
        //搜索日期大于等于今天
        if(DateUtil.judgeDateStrIsGteThatDay(resultDate)){
            throw new BusinessException("attendanceData.is.null");
        }

        //要返回的数据
        List<AbnormalUserView> abnormalUserList = new ArrayList<>();

        //当前部门的人员信息
        ClassificationInfo classificationInfo = this.usersService.selectNewMailListByScale();

        if(classificationInfo==null){
            throw new BusinessException("teamUsers.is.null");
        }

        /** 获取部门信息 */
        Team team = classificationInfo.getTeam();
        //部门id
        String teamId = team.getId();
        //部门级别
        Short teamLevel = team.getTeamLevel();

        List<Users> departmentalStaffs = classificationInfo.getDepartmentalStaffs();

        if(teamLevel.intValue()==1){
            System.err.println("一级部门通讯录="+departmentalStaffs);
        }

        departmentalStaffs.forEach(users -> {
            //要判断是否加入了考勤组
            String userId = users.getId();
            AbnormalUserView abnormalUserView = new AbnormalUserView()
                    .setUserId(userId)
                    .setHeadPicUrl(users.getFileUpload().getUrl())
                    .setName(users.getNickName())
                    .setWorkerNum(users.getWorkerNum())
                    .setTeamId(teamId)
                    .setTeamLevel(teamLevel);
            abnormalUserList.add(abnormalUserView);
        });

        //只要不是三级部门，就要循环
        if(teamLevel.intValue()!=3){
            //查询下级部门员工
            List<ClassificationInfo> list = this.usersService.selectMailListByTeamId(teamId);

            list.forEach(classificationInfo1 -> {
                Team newTeam = classificationInfo1.getTeam();
                List<Users> newTeamStaffs = classificationInfo1.getDepartmentalStaffs();

                newTeamStaffs.forEach(users -> {
                    System.err.println("-----------------------------------------");
                    System.err.println("异常员工-"+users.getId());
                    AbnormalUserView abnormalUserView = new AbnormalUserView()
                            .setUserId(users.getId())
                            .setHeadPicUrl(users.getFileUpload().getUrl())
                            .setName(users.getNickName())
                            .setWorkerNum(users.getWorkerNum())
                            .setTeamId(newTeam.getId())
                            .setTeamLevel(newTeam.getTeamLevel());
                    abnormalUserList.add(abnormalUserView);

                });

                //如果仍然不是三级部门,继续循环
                if(newTeam.getTeamLevel().intValue()!=3){
                    List<ClassificationInfo> list1 = this.usersService.selectMailListByTeamId(newTeam.getId());
                    list1.forEach(classificationInfo2 -> {
                        Team newTeam2 = classificationInfo2.getTeam();
                        List<Users> newTeamStaffs2 = classificationInfo2.getDepartmentalStaffs();
                        newTeamStaffs2.forEach(users -> {
                            AbnormalUserView abnormalUserView = new AbnormalUserView()
                                    .setUserId(users.getId())
                                    .setHeadPicUrl(users.getFileUpload().getUrl())
                                    .setName(users.getNickName())
                                    .setWorkerNum(users.getWorkerNum())
                                    .setTeamId(newTeam2.getId())
                                    .setTeamLevel(newTeam2.getTeamLevel());
                            abnormalUserList.add(abnormalUserView);
                        });
                    });
                }
            });
        }
        //存放考勤正常的考勤记录，待删除
        List<AbnormalUserView> removeAbnormalUserList = new ArrayList<>();

        /** 先删除没有考勤记录的，没有考勤记录说明没加入考勤组或者 非考勤工作日*/
        abnormalUserList.forEach(abnormalUserView -> {
            String userId = abnormalUserView.getUserId();
            //该用户查询日期的考勤记录
            AttendanceRecord attendanceRecord = this.attendanceRecordService.selectAttendanceRecordByUserIdAndDateOfAttendance(userId,LocalDate.parse(resultDate));
            if(attendanceRecord==null){
                removeAbnormalUserList.add(abnormalUserView);
            }
        });
        //删除考勤记录为空的
        abnormalUserList.removeAll(removeAbnormalUserList);
        //再清空一次，存放下面的正常考勤记录
        removeAbnormalUserList.clear();

        /** 然后再来删除正常考勤的，进行统计*/
        abnormalUserList.forEach(abnormalUserView -> {
            String userId = abnormalUserView.getUserId();
            //该用户查询日期的考勤记录
            AttendanceRecord attendanceRecord = this.attendanceRecordService.selectAttendanceRecordByUserIdAndDateOfAttendance(userId,LocalDate.parse(resultDate));

            String attendanceStatus = attendanceRecord.getFinalAttendanceStatus();
            if(attendanceStatus.equals("2") || attendanceStatus.equals("4") || attendanceStatus.equals("8")){
                //缺卡
                abnormalUserView.setAbnormalState(VariableConstants.STRING_CONSTANT_1);
            }else if(attendanceStatus.equals("5")){
                //矿工
                abnormalUserView.setAbnormalState(VariableConstants.STRING_CONSTANT_2);
            }else{
                //正常的考勤
                removeAbnormalUserList.add(abnormalUserView);
            }
        });

        //计算考勤率
        double attendanceRate = getAttendanceRate(removeAbnormalUserList.size(),abnormalUserList.size());
        System.err.println("removeAbnormalUserList="+removeAbnormalUserList);
        abnormalUserList.removeAll(removeAbnormalUserList);
        AttendanceMonitoringView attendanceMonitoringView = new AttendanceMonitoringView()
                .setAttendanceRate(attendanceRate).setAbnormalUserList(abnormalUserList);

//        System.err.println("-------考勤监控-------");
//        System.err.println(JSON.toJSON(attendanceMonitoringView));
        return attendanceMonitoringView;
    }

    /**
     * @方法名：getAttendanceRate
     * @描述： 计算考勤率
     * @作者： kjz
     * @日期： Created in 2020/4/20 17:56
     */
    public double getAttendanceRate(int normality, int sum) {
        System.err.println("正常考勤数量="+normality);
        System.err.println("总数量="+sum);
        /*if(sum==0 || normality==sum){
            return "100%";
        }else if(normality==0){
            return "0%";
        }else{
            double result = (double) normality/sum;
            System.err.println("考勤率="+result);
            return DataUtil.getPercentFormat(result,2,2);
        }*/
        if(sum==0 || normality==sum){
            return 1;
        }else if(normality==0){
            return 0;
        }else{
            double result = (double) normality/sum;
            System.err.println("考勤率="+result);
            return result;
        }
    }


}
